<template>
  <div class="">
    <a-tabs
      v-model:activeKey="activeKey"
      class="user"
      centered
      size="medium"
      :tabBarStyle="{ fontWeight: 'bold', marginBottom: '20px' }"
      @change="selectTab"
    >
      <a-tab-pane key="1" tab="用户信息">
        <a-button type="primary" style="margin: 10px 0px 30px 0px" @click="edit"
          >编辑</a-button
        >
        <a-card title="基本信息">
          <!-- <a-row> -->
          <!-- <a-col :span="2"> -->
          <a-avatar :size="64" :src="user.avatarJson">
            <template #icon><UserOutlined /></template>
          </a-avatar>
          <!-- </a-col> -->
          <!-- <a-col :span="8"> -->
          <a-descriptions
            bordered
            :column="{ xxl: 3, xl: 3, lg: 3, md: 1, sm: 1, xs: 1 }"
          >
            <a-descriptions-item label="用户昵称">{{
              user.nick
            }}</a-descriptions-item>
            <a-descriptions-item label="用户ID">{{
              user.userId
            }}</a-descriptions-item>
            <a-descriptions-item label="手机号码">{{
              user.mobile
            }}</a-descriptions-item>
            <a-descriptions-item label="性别">{{
              user.sex
            }}</a-descriptions-item>
            <a-descriptions-item label="生日">{{
              user.birthday
            }}</a-descriptions-item>
            <!-- </a-descriptions> -->
            <!-- </a-col> -->
            <!-- <a-col :span="10" :offset="2"> -->
            <!-- <a-descriptions
              bordered
              :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
            > -->
            <a-descriptions-item label="真实姓名">{{
              user.realName ? user.realName : "未实名"
            }}</a-descriptions-item>
            <a-descriptions-item label="身份证号">{{
              user.idCard ? user.idCard : "未实名"
            }}</a-descriptions-item>
            <a-descriptions-item label="注册渠道">{{
              user.registSource
            }}</a-descriptions-item>
            <a-descriptions-item label="注册时间">{{
              user.createdAt
            }}</a-descriptions-item>
            <!-- <a-descriptions-item label="地理位置">{{user.addressData}}</a-descriptions-item> -->
          </a-descriptions>
        </a-card>
        <a-card title="账户信息" style="margin-top: 20px">
          <a-descriptions
            bordered
            :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
          >
            <a-descriptions-item label="订单数量">{{
              user.orderNumber ? user.orderNumber : 0
            }}</a-descriptions-item>
            <a-descriptions-item label="消费金额">{{
              user.orderPriceSum ? user.orderPriceSum : 0
            }}</a-descriptions-item>
            <a-descriptions-item label="可用优惠券">{{
              user.haveTicketNum ? user.haveTicketNum : 0
            }}</a-descriptions-item>
            <a-descriptions-item label="已用优惠券">{{
              user.usedTicketNum ? user.usedTicketNum : 0
            }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
        <!-- </a-col> -->
        <!-- </a-row> -->
      </a-tab-pane>
      <a-tab-pane key="2" tab="我的订单">
        <a-table
          :columns="columns"
          :data-source="order"
          bordered
          :loading="orderLoading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #status="{ record }">
            <a-button type="link" @click="look(record.key)">
              {{ orderListStatus(record.status) }}
            </a-button>
          </template>
          <template #operation="{ record }">
            <a-button
              type="link"
              @click="look(record.number)"
              v-has="{ a: $route, b: 1 }"
              >查看</a-button
            >
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="3" tab="地址管理">
        <a-table
          :columns="addressColumns"
          :data-source="address"
          bordered
          :loading="addressLoading"
          :pagination="false"
        >
          <!-- <template #operation="{ record }">
            <a-button type="danger" @click="delAddress(record.key)"
              >删除</a-button
            >
          </template> -->
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="4" tab="健康档案">
        <a-list
          :grid="{ gutter: 16, xs: 1, sm: 2, md: 4, lg: 4, xl: 6, xxl: 3 }"
          :data-source="health"
        >
          <template #renderItem="{ item, index }">
            <a-list-item>
              <a-card :title="index + 1" hoverable>
                <template #extra
                  ><a-button type="link" @click="lookHealth(item.id)"
                    >查看</a-button
                  ></template
                >
                <div class="list"><a-tag>姓名:</a-tag>{{ item.realName }}</div>
                <div class="list"><a-tag>性别:</a-tag>{{ item.sex }}</div>
                <div class="list">
                  <a-tag color="cyan">关系:</a-tag>{{ item.familyRelation }}
                </div>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </a-tab-pane>
      <a-tab-pane key="5" tab="登录日志">
        <a-table
          :columns="columnsLogin"
          :data-source="logList"
          bordered
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #status="{ record }">
            <div>{{ orderListStatus(record.status) }}</div>
          </template>
          <template #status1="{ record }">
            <div>{{ ComsumeStatus(record.status) }}</div>
          </template>
          <template #operation="{ record }">
            <a-button
              type="link"
              @click="look(record, record.status)"
              v-has="{ a: $route, b: 2 }"
              >查看</a-button
            >
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <!-- 编辑护士信息 -->
    <a-modal
      :visible="visible"
      title="编辑资料"
      :footer="null"
      @cancel="cancel"
      width="50%"
    >
      <a-form ref="formRef" :label-col="labelCol" :rules="rules" :model="form">
        <a-form-item label="手机号码" name="mobile">
          <a-input
            v-model:value="form.mobile"
            placeholder="请输入手机号码"
          ></a-input>
        </a-form-item>
        <a-form-item label="用户昵称">
          <a-input
            v-model:value="form.nick"
            placeholder="请输入用户昵称"
          ></a-input>
        </a-form-item>

        <!-- <a-form-item label="账号启用状态">
          <a-switch
            v-model:checked="form.isDele"
            :checkedValue="1"
            :unCheckedValue="0"
            @change="changeStatus"
          />
        </a-form-item> -->
      </a-form>
      <a-row>
        <a-col :span="4" :offset="8">
          <a-button type="primary" @click="submit">提交</a-button>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-button type="info" @click="cancel">关闭</a-button>
        </a-col>
      </a-row>
    </a-modal>

    <!-- 健康档案 -->
    <template v-if="healthVisible">
      <health
        :visible="healthVisible"
        :id="id"
        @closeModal="closeHealth"
      ></health>
    </template>
  </div>
</template>
<script>
import {
  reactive,
  ref,
  watch,
  computed,
  defineComponent,
  createVNode,
  toRefs,
} from "vue";
import { Modal, notification } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
import { UserOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import Health from "@/components/order/Health";
import { validatorPhone } from "@/assets/js/validate";
import addressData from "@/assets/js/address.js";
import {
  selectUserInfo,
  selectAllHealthFile,
  selectOrderByUserId,
  updateUser,
  selectUserAddress,
  selectLoginRecord,
} from "@/api/user/index";
import { useModal } from "@/hooks"
export default {
  components: {
    UserOutlined,
    Health,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const userId = ref("");
    userId.value = route.query.id;

    const visible = ref(false);
    const formRef = ref("");
    const data = reactive({
      user: {},
      order: [],
      address: [],
      health: [],
      userLoading: true,
      orderLoading: true,
      addressLoading: true,
      form: {},
      id: "", //健康档案ID
      logList: [],
    });
    const healthVisible = ref(false);
    const rules = {
      mobile: [{ required: true, validator: validatorPhone }],
    };

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    const columnsLogin = [
      {
        title: "时间",
        dataIndex: "loginTime",
        className: "table",
        align: "center",
      },
      {
        title: "IP",
        dataIndex: "ip",
        className: "table",
        align: "center",
        sort: true,
      },
      {
        title: "地区",
        dataIndex: "address",
        className: "table",
        align: "center",
      },
      {
        title: "登录方式",
        dataIndex: "loginType",
        className: "table",
        align: "center",
      },
    ];
    const columns = [
      {
        title: "订单号",
        dataIndex: "number",
        className: "table",
        align: "center",
      },
      {
        title: "服务名称",
        dataIndex: "serviceName",
        className: "table",
        align: "center",
        sort: true,
      },
      {
        title: "下单时间",
        dataIndex: "createdAt",
        className: "table",
        align: "center",
        sort: true,
      },
      {
        title: "订单金额",
        dataIndex: "price",
        className: "table",
        align: "center",
      },
      {
        title: "服务次数",
        dataIndex: "num",
        className: "table",
        align: "center",
      },
      {
        title: "订单状态",
        dataIndex: "status",
        className: "table",
        align: "center",
        slots: {
          customRender: "status",
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        align: "center",
        fixed: "right",
        slots: {
          customRender: "operation",
        },
      },
    ];
    const orderListStatus = (status) => {
      let title = "";
      switch (status) {
        case 1:
          title = "待付款";
          break;
        case 2:
          title = "待接单";
          break;
        case 3:
          title = "待服务";
          break;
        case 4:
          title = "进行中"; //服务中
          break;
        case 5:
          title = "已完成";
          break;
        case 6:
          title = "已取消";
          break;
        case 7:
          title = "已退款";
          break;
        case 9:
          title = "退款中";
          break;
        default:
          break;
      }
      return title;
    };
    const addressColumns = [
      {
        title: "地址",
        dataIndex: "address",
        className: "table",
        align: "center",
      },
      // {
      //   title: "操作",
      //   dataIndex: "operation",
      //   className: "table",
      //   align: "center",
      //   fixed: "right",
      //   slots: {
      //     customRender: "operation",
      //   },
      // },
    ];

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      page.current = pagination.current;
      page.pageSize = pagination.pageSize;

      // 请求列表接口
      getOrderList();
    };
    const closeModal = () => {
      visible.value = false;
    };
    const selectTab = (e) => {
      console.log(e);
      page.current = 1;
      if (e == 2) {
        // 订单
        getOrderList();
      } else if (e == 3) {
        // 地址
        getAddressList();
      } else if (e == 4) {
        // 健康档案
        getHealthList();
      } else if (e == 5) {
        initLog();
      }
    };
    const submit = () => {
      formRef.value.validate().then((res) => {
        console.log(data.form, "表单内容");

        updateUser(data.form).then((result) => {
          if (result.success) {
            visible.value = false;
            notification.success({ message: "更改成功", duration: 1 });
            initUserInfo();
          }
        });
      });
    };
    // 是否停用
    const changeStatus = () => {};
    // 编辑用户信息
    const edit = () => {
      visible.value = true;
      data.form = {
        mobile: data.user.mobile,
        nick: data.user.nick,
        id: data.user.userId,
      };
    };
    // 关闭
    const cancel = () => {
      visible.value = false;
    };
    // 删除地址
    const delAddress = () => {
      const {closeModal} = useModal.confirm({
        title: "确定删除当前用户的地址吗?",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
      });
    };
    // 查看健康档案
    const lookHealth = (e) => {
      healthVisible.value = true;
      data.id = e;
    };
    const closeHealth = () => {
      healthVisible.value = false;
    };
    const look = (key) => {
      router.push({
        path: "/order/center/order-detail",
        query: {
          isEdit: 0,
          number: key,
        },
      });
    };
    initUserInfo();
    async function initUserInfo() {
      let res = await selectUserInfo(userId.value);
      if (res.success) {
        data.user = res.object;
      }
    }
    async function getOrderList() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        userId: userId.value,
      };
      let res = await selectOrderByUserId(obj);
      if (res.success) {
        res.object.records.forEach((el) => (el.key = el.number));
        data.order = res.object.records;
        page.total = res.object.total;
        data.orderLoading = false;
      }
    }
    async function getAddressList() {
      let res = await selectUserAddress(userId.value);
      if (res.success) {
        data.address = res.object;
        data.addressLoading = false;
      }
    }
    async function getHealthList() {
      let res = await selectAllHealthFile(userId.value);
      if (res.success) {
        data.health = res.object;
      }
    }
    async function initLog() {
      // 用户登录日志
      let res = await selectLoginRecord({
        loginId: userId.value,
        userType: 2,
        pageNum: page.current,
        pageSize: page.pageSize,
      });
      if (res.success) {
        data.loading = false;
        res.object.list.forEach((el) => (el.key = el.id));
        data.logList = res.object.list;
        page.total = res.object.total;
      }
    }
    return {
      ...toRefs(data),
      activeKey: ref("1"),
      pagination,
      handleTableChange,
      columns,
      columnsLogin,
      look,
      edit,
      visible,
      labelCol: { style: { fontWeight: "bolder", width: "100px" } },
      formRef,
      rules,
      changeStatus,
      closeModal,
      value: ref([]),
      addressColumns,
      delAddress,
      healthVisible,
      lookHealth,
      closeHealth,
      cancel,
      selectTab,
      submit,
      orderListStatus,
    };
  },
};
</script>
<style scoped>
.list {
  margin-bottom: 10px;
}
</style>
